//
//  UITextField+placeHolder.m
//  TestYoho
//
//  Created by YiDarren on 17/2/3.
//  Copyright © 2017年 YiDarren. All rights reserved.
//

#import "UITextField+placeHolder.h"
#import <objc/message.h>

static NSString *const placeholderColorName = @"placeholderColor";

@implementation UITextField (placeHolder)

+(void)load {
    
    Method setPlaceholder = class_getInstanceMethod(self, @selector(setPlaceholder:));
    
    Method bs_setPlaceholder =  class_getInstanceMethod(self, @selector(bs_setPlaceholder:));
    
    method_exchangeImplementations(setPlaceholder, bs_setPlaceholder);
    
}


-(void)setPlaceholderColor:(UIColor *)placeholderColor {
    //此方法的四个参数分别为：源对象、关键字、关联的对象、关联策略。
    //关键字是一个void类型的指针，每个关联的关键字必须是唯一的，通常用静态变量作为关键字
    //关联策略表明了相关的对象是通过赋值，保留引用还是复制的方式进行关联的
    objc_setAssociatedObject(self, (__bridge const void *)(placeholderColorName), placeholderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    //设置占位文字颜色 placeholderLabel是UITextField的属性之一
    UILabel *placeholderLabel = [self valueForKeyPath:@"placeholderLabel"];
    
    //NSLog(@"placeholderLabel = %@", [self valueForKeyPath:@"placeholderLabel"]);
    
    placeholderLabel.textColor = placeholderColor;
    
}

- (UIColor *)placeholderColor {
    
    //返回关联
    return objc_getAssociatedObject(self, (__bridge void *)placeholderColorName);
}

-(void)bs_setPlaceholder:(NSString *)placeholder {
    
    //1
    [self bs_setPlaceholder:placeholder];
    
    //2
    self.placeholderColor = self.placeholderColor;
}




//
//+(void)load {
//    
//    //获取setPlaceholder
//    Method setPlaceholder = class_getInstanceMethod(self, @selector(setPlaceholder:));
//    //获取bs_setPlaceholder
//    Method bs_setPlaceholder = class_getInstanceMethod(self, @selector(bs_setPlaceholder:));
//    
//    //交换方法
//    method_exchangeImplementations(setPlaceholder, bs_setPlaceholder);
//}
//
//-(void)setPlaceholderColor:(UIColor *)placeholderColor {
//    
//    //设置关联
//    objc_setAssociatedObject(self, (__bridge const void *)(placeholderColorName), placeholderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
//
//    //设置展位文字颜色
//    UILabel *placeholderLabel = [self valueForKeyPath:@"placeholderLabel"];
//
//    placeholderLabel.textColor = placeholderColor;
//}
//
//- (UIColor *)placeholderColor {
//    
//    //返回关联
//    return objc_getAssociatedObject(self, (__bridge const void *)(placeholderColorName));
//}
//
//// 设置占位文字,并且设置占位文字颜色
//-(void)bs_setPlaceholder:(NSString *)placeholder {
//    
//    //1、设置占位文字
//    [self bs_setPlaceholder:placeholder];
//    
//    //2、设置占位文字颜色
//    self.placeholderColor = self.placeholderColor;
//}
//

@end
